package network;

import java.io.IOException;
import java.net.BindException;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

/**
 * 客户连接服务器时可能抛出的异常<br><br>
 *
 * remoteAddr=localhost, port=25 Bind Exception<br>
 * remoteAddr=localhosy, port=8888 Connect Exception<br>
 * remoteAddr=www.baidu.com, port=8888 SocketTimeout Exception<br>
 *
 */
public class ConnectExcepttion {

	public void connect(String host, int port){
		SocketAddress remoteAddress = new InetSocketAddress(host, port);
		Socket socket = null;
		String result = "";
		try{
			long loginTime = System.currentTimeMillis();
			socket = new Socket();
//			socket.bind(address);	//BindException
			socket.connect(remoteAddress, 1000);
			long end = System.currentTimeMillis();
			result = (end - loginTime) + "ms";
		}catch(BindException be){
			result = "can't not bind local address and port";
		}catch(UnknownHostException he){
			result = "unknown host";
		}catch(ConnectException ce){
			result = "connection refuse";
		}catch(SocketTimeoutException se){
			result = "time out";
		}catch(IOException ioe){
			result = "failure";
		}finally{
			try{
				if(socket != null){
					socket.close();
				}
			}catch(IOException ios){
				System.out.println();
			}
		}
		System.out.println("result = " + socket + ":" +result);
	}


	public static void main(String[] args) {
		String host = "localhost";
		int port = 8888;
		if(args.length > 1){
			host = args[0];
			port = Integer.parseInt(args[1]);
		}
		new ConnectExcepttion().connect(host, port);
	}

}
